const { ccclass, property } = cc._decorator;

export interface IConfigData {
    item: { id: number; name: string }[];
    level: ILevelConfig[];
}

export interface ILevelConfig {
    id: number;
    total: number;
    col: number;
    itemid: string;
}

@ccclass
export default class Config extends cc.Component {
    private static _instance: Config = null;

    private configs: IConfigData = null;

    public static get instance() {
        if (this._instance === null) {
            this._instance = new this();
        }
        return this._instance;
    }

    public init() {
        const now = Date.now();
        const self = this;
        return new Promise<any>(function (resolve, reject) {
            cc.resources.load('config/all', cc.JsonAsset, function (err, obj) {
                if (err) {
                    cc.error(err.message || err);
                    return;
                }
                console.log(`Config.getAllConfig()===>初始化配置:${Date.now() - now}ms`, obj);

                self.configs = obj.json;
                resolve(self.configs);
            });
        });
    }

    public async get<T extends keyof IConfigData>(name: T): Promise<IConfigData[T]> {
        if (!this.configs) {
            this.configs = await this.init();
            return this.configs[name];
        } else {
            return this.configs[name];
        }
    }

    public async getLevelConfigById(level: number) {
        const config = await this.get('level');
        const arr = Object.keys(config).map(key => config[key]);
        if (level > arr.length - 1) {
            level = arr.length - 1;
        }
        // '1/2/3'===>[1,2,3]
        const temp = arr.find((o) => o.id === level);
        const ids = [];
        temp.itemId.split('/').forEach((o) => {
            ids.push(Number(o));
        });
        const data: { id: number, total: number, col: number, itemId: number[] } = {
            id: temp.id,
            total: temp.total,
            col: temp.col,
            itemId: ids,
        };
        return data;
    }
}